import sys
import re
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QTextEdit, QPushButton, QLabel, QLineEdit, QFileDialog,
    QMessageBox, QSplitter, QCheckBox, QGroupBox, QGridLayout, QToolTip
)
from PyQt6.QtCore import Qt, QPoint
from PyQt6.QtGui import QEnterEvent, QFont, QIcon, QColor
from PyQt6.QtGui import QPalette


class TextSplitterApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("文本分割工具")
        self.setGeometry(100, 30, 900, 790)
        self.setWindowIcon(QIcon("icon.png"))  # 请准备一个icon.png文件或移除这行
        self.init_ui()
        self.setup_styles()

    def init_ui(self):
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        
        main_layout = QVBoxLayout()
        main_layout.setContentsMargins(12, 12, 12, 12)
        main_layout.setSpacing(12)
        main_widget.setLayout(main_layout)
        
        # 控制区域
        control_group = QGroupBox("分隔控制")
        control_layout = QHBoxLayout()
        control_layout.setContentsMargins(10, 10, 10, 10)
        control_layout.setSpacing(10)
        
        self.delimiter_label = QLabel("分隔符:")
        self.delimiter_label.setFont(QFont("Microsoft YaHei", 10))
        self.delimiter_input = QLineEdit()
        self.delimiter_input.setFont(QFont("Consolas", 10))
        self.delimiter_input.setPlaceholderText("输入分隔符，多个字符用|分隔")
        self.delimiter_input.setMinimumWidth(250)
        
        self.split_button = QPushButton("分割文本")
        self.split_button.setFont(QFont("Microsoft YaHei", 10, QFont.Weight.Bold))
        self.split_button.setToolTip("点击分割当前文本")
        self.split_button.clicked.connect(self.split_text)
        
        self.clear_button = QPushButton("清空")
        self.clear_button.setFont(QFont("Microsoft YaHei", 10))
        self.clear_button.setToolTip("清空分隔符输入框")
        self.clear_button.clicked.connect(self.clear_delimiter)
        
        control_layout.addWidget(self.delimiter_label)
        control_layout.addWidget(self.delimiter_input)
        control_layout.addWidget(self.split_button)
        control_layout.addWidget(self.clear_button)
        control_group.setLayout(control_layout)
        
        # 过滤选项
        self.filter_group = QGroupBox("文本清理选项")
        self.filter_group.setFont(QFont("Microsoft YaHei", 10))
        filter_layout = QGridLayout()
        filter_layout.setContentsMargins(10, 15, 10, 15)
        filter_layout.setSpacing(12)
        
        self.remove_numbers = QCheckBox("删除数字")
        self.remove_symbols = QCheckBox("删除所有符号（除分隔符）")
        self.remove_non_chinese = QCheckBox("删除非中文字符")
        self.remove_chinese = QCheckBox("删除中文字符（包括中文标点）")
        
        for cb in [self.remove_numbers, self.remove_symbols, 
                  self.remove_non_chinese, self.remove_chinese]:
            cb.setFont(QFont("Microsoft YaHei", 9))
        
        filter_layout.addWidget(self.remove_numbers, 0, 0)
        filter_layout.addWidget(self.remove_symbols, 0, 1)
        filter_layout.addWidget(self.remove_non_chinese, 1, 0)
        filter_layout.addWidget(self.remove_chinese, 1, 1)
        self.filter_group.setLayout(filter_layout)
        
        # 常用分隔符 - 中文符号
        self.cn_delimiters_group = QGroupBox("中文分隔符")
        self.cn_delimiters_group.setFont(QFont("Microsoft YaHei", 10))
        cn_delimiters_layout = QHBoxLayout()
        cn_delimiters_layout.setContentsMargins(8, 8, 8, 8)
        cn_delimiters_layout.setSpacing(6)
        
        cn_delimiter_buttons = [
            ("、", "、", "顿号"),
            ("，", "，", "中文逗号"),
            ("。", "。", "中文句号"),
            ("；", "；", "分号"),
            ("：", "：", "冒号"),
            ("！", "！", "感叹号"),
            ("？", "？", "问号"),
            ("空格", " ", "空格字符(\\s)"),
            ("换行", "\n", "换行符(\\n)")
        ]
        
        for display_text, actual_char, tooltip in cn_delimiter_buttons:
            btn = self.create_delimiter_button(display_text, actual_char, tooltip)
            cn_delimiters_layout.addWidget(btn)
        
        self.cn_delimiters_group.setLayout(cn_delimiters_layout)
        
        # 常用分隔符 - 英文符号
        self.en_delimiters_group = QGroupBox("英文分隔符")
        self.en_delimiters_group.setFont(QFont("Microsoft YaHei", 10))
        en_delimiters_layout = QHBoxLayout()
        en_delimiters_layout.setContentsMargins(8, 8, 8, 8)
        en_delimiters_layout.setSpacing(6)
        
        en_delimiter_buttons = [
            (",", ",", "英文逗号"),
            (".", ".", "英文句号"),
            (";", ";", "英文分号"),
            (":", ":", "英文冒号"),
            ("!", "!", "英文感叹号"),
            ("?", "?", "英文问号")
        ]
        
        for display_text, actual_char, tooltip in en_delimiter_buttons:
            btn = self.create_delimiter_button(display_text, actual_char, tooltip)
            en_delimiters_layout.addWidget(btn)
        
        self.en_delimiters_group.setLayout(en_delimiters_layout)
        
        # 文件操作按钮
        file_buttons_layout = QHBoxLayout()
        file_buttons_layout.setSpacing(10)
        
        self.load_button = QPushButton("📂 加载文件")
        self.save_button = QPushButton("💾 保存结果")
        
        for btn in [self.load_button, self.save_button]:
            btn.setFont(QFont("Microsoft YaHei", 10))
            btn.setCursor(Qt.CursorShape.PointingHandCursor)
            btn.setMinimumWidth(120)
        
        self.load_button.clicked.connect(self.load_file)
        self.save_button.clicked.connect(self.save_result)
        
        file_buttons_layout.addWidget(self.load_button)
        file_buttons_layout.addWidget(self.save_button)
        
        # 文本编辑区域
        splitter = QSplitter(Qt.Orientation.Vertical)
        splitter.setHandleWidth(5)
        
        self.original_text = QTextEdit()
        self.original_text.setFont(QFont("Microsoft YaHei", 10))
        self.original_text.setPlaceholderText("在此输入或粘贴要分割的文本...")
        
        self.result_text = QTextEdit()
        self.result_text.setFont(QFont("Microsoft YaHei", 10))
        self.result_text.setPlaceholderText("分割结果将显示在这里...")
        self.result_text.setReadOnly(True)
        
        splitter.addWidget(self.original_text)
        splitter.addWidget(self.result_text)
        splitter.setSizes([350, 350])
        
        # 组装主界面
        main_layout.addWidget(control_group)
        main_layout.addWidget(self.filter_group)
        
        # 分隔符组布局
        delimiters_layout = QVBoxLayout()
        delimiters_layout.setSpacing(8)
        delimiters_layout.addWidget(self.cn_delimiters_group)
        delimiters_layout.addWidget(self.en_delimiters_group)
        main_layout.addLayout(delimiters_layout)
        
        main_layout.addLayout(file_buttons_layout)
        main_layout.addWidget(splitter)

    def create_delimiter_button(self, display_text, actual_char, tooltip):
        btn = QPushButton(display_text)
        btn.setFont(QFont("Microsoft YaHei", 9))
        btn.setToolTip(f"{tooltip} (实际字符: {repr(actual_char)})")
        btn.setCursor(Qt.CursorShape.PointingHandCursor)
        btn.setMinimumWidth(40)
        btn.clicked.connect(lambda _, d=actual_char: self.add_delimiter(d))
        
        btn.setMouseTracking(True)
        def enter_event(event, t=tooltip, c=actual_char):
            self.show_tooltip(event, f"{t} (实际字符: {repr(c)})")
        btn.enterEvent = enter_event
        
        return btn

    def setup_styles(self):
        # 设置主窗口样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f2f5;
            }
            QGroupBox {
                border: 1px solid #d1d5db;
                border-radius: 6px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px;
                color: #4b5563;
            }
            QTextEdit, QLineEdit {
                border: 1px solid #d1d5db;
                border-radius: 4px;
                padding: 6px;
                background: white;
                selection-background-color: #3b82f6;
                selection-color: white;
            }
            QPushButton {
                border: 1px solid #d1d5db;
                border-radius: 4px;
                padding: 5px 12px;
                background-color: #f9fafb;
                color: #374151;
                min-width: 40px;
            }
            QPushButton:hover {
                background-color: #e5e7eb;
                border-color: #9ca3af;
            }
            QPushButton:pressed {
                background-color: #d1d5db;
            }
            QCheckBox {
                spacing: 6px;
                color: #374151;
            }
            QCheckBox::indicator {
                width: 16px;
                height: 16px;
            }
            QSplitter::handle {
                background: #d1d5db;
            }
        """)
        
        # 特殊按钮样式
        self.split_button.setStyleSheet("""
            QPushButton {
                background-color: #3b82f6;
                border: 1px solid #2563eb;
                color: white;
            }
            QPushButton:hover {
                background-color: #2563eb;
            }
            QPushButton:pressed {
                background-color: #1d4ed8;
            }
        """)
        
        # 文件操作按钮样式
        for btn in [self.load_button, self.save_button]:
            btn.setStyleSheet("""
                QPushButton {
                    background-color: #4b5563;
                    border: 1px solid #374151;
                    color: white;
                }
                QPushButton:hover {
                    background-color: #374151;
                }
                QPushButton:pressed {
                    background-color: #1f2937;
                }
            """)
        
        # 设置文本区域样式
        self.result_text.setStyleSheet("""
            QTextEdit {
                background-color: #f8fafc;
            }
        """)

    def show_tooltip(self, event: QEnterEvent, description: str):
        global_pos = event.globalPosition()
        QToolTip.showText(QPoint(int(global_pos.x()), int(global_pos.y())), description)
    
    def add_delimiter(self, delimiter):
        current = self.delimiter_input.text()
        # 特殊处理：空格显示为\s，换行符显示为\n
        display_delim = {
            " ": r"\s",
            "\n": r"\n"
        }.get(delimiter, delimiter)
        
        if current:
            self.delimiter_input.setText(f"{current}|{display_delim}")
        else:
            self.delimiter_input.setText(display_delim)

    def clear_delimiter(self):
        self.delimiter_input.clear()

    def split_text(self):
        text = self.original_text.toPlainText()
        if not text.strip():
            QMessageBox.warning(self, "警告", "请输入要分割的文本！")
            return

        raw_delimiters = self.delimiter_input.text()
        delimiters = []
        if raw_delimiters:
            for d in raw_delimiters.split("|"):
                # 将显示的\s和\n转换回实际字符
                processed_d = {
                    r"\s": " ",
                    r"\n": "\n"
                }.get(d, d)
                if d:
                    delimiters.append(processed_d)

        if not delimiters:
            QMessageBox.warning(self, "警告", "请输入有效的分隔符！")
            return

        try:
            text = text.strip()
            
            pattern_parts = []
            for d in delimiters:
                if d == " ":
                    pattern_parts.append(r"\s+")
                else:
                    pattern_parts.append(re.escape(d))
            
            pattern = "|".join(pattern_parts)
            if len(delimiters) > 1:
                pattern = f"[{pattern}]+"
            else:
                pattern += "+"

            parts = re.split(pattern, text)
            parts = [p.strip() for p in parts if p.strip()]

            result = []
            for part in parts:
                cleaned = part
                
                if self.remove_numbers.isChecked():
                    cleaned = re.sub(r"\d+", "", cleaned)
                
                if self.remove_symbols.isChecked():
                    safe_chars = [re.escape("".join(delimiters))]
                    cleaned = re.sub(
                        fr'[^\w\s\x27{"".join(safe_chars)}]', 
                        '', 
                        cleaned
                    )
                
                if self.remove_chinese.isChecked():
                    cleaned = re.sub(r"[\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]", "", cleaned)
                elif self.remove_non_chinese.isChecked():
                    cleaned = re.sub(r"[^\u4e00-\u9fa5\u3000-\u303f\uff00-\uffef]", "", cleaned)

                cleaned = cleaned.strip()
                if cleaned:
                    result.append(cleaned)

            self.result_text.setPlainText("\n".join(result))

        except Exception as e:
            QMessageBox.critical(self, "错误", f"处理过程中发生错误：{str(e)}")

    def load_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "打开文件", "", "文本文件 (*.txt);;所有文件 (*)")
        if file_path:
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    self.original_text.setPlainText(f.read())
            except Exception as e:
                QMessageBox.critical(self, "错误", f"无法读取文件：{str(e)}")

    def save_result(self):
        result = self.result_text.toPlainText()
        if not result.strip():
            QMessageBox.warning(self, "警告", "没有需要保存的内容！")
            return

        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存文件", "", "文本文件 (*.txt);;所有文件 (*)")
        if file_path:
            try:
                with open(file_path, "w", encoding="utf-8") as f:
                    f.write(result)
                QMessageBox.information(self, "成功", "文件保存成功！")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存文件失败：{str(e)}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用程序字体
    font = QFont("Microsoft YaHei", 9)
    app.setFont(font)
    
    window = TextSplitterApp()
    window.show()
    sys.exit(app.exec())